package com.tomcat.mesos.utils;

import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author Rayn on 2015/12/23 22:01
 * @email liuwei412552703@163.com
 */
public class NetWorkUtils {

    private static final Logger LOG = LoggerFactory.getLogger(NetWorkUtils.class);
    /**
     * 端口是否可用
     *
     * @param port
     * @param facetor
     * @return
     */
    public static boolean isFreePort(int port, int facetor){
        boolean flag = false;
        try {
            Socket socket = new Socket(InetAddress.getLocalHost(), port);
            socket.close();
            flag = true;
        } catch (ConnectException e) {
            return true;
        }  catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 获取可用的端口
     * @return
     */
    public static int getUsedPort(int port, int facetor){

        while(true){
            boolean flag = isFreePort(port, facetor);
            if(flag){
                break;
            }
            LOG.warn("端口：" + port + " 被占用，重新获取其他可用端口");
            port += facetor;
        }
        return port;
    }


    public static void main(String[] args) {
        int port = NetWorkUtils.getUsedPort(135, 1);
        System.out.println(port);


    }
}
